import { BadGatewayException, Body, Controller, Ip, Post, Req, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';
import { User } from 'src/decorator/user.decorator';
import { BaoMinModel } from 'src/mongodb/models/baominModel/BaoMinModel';
import { JobModel } from 'src/mongodb/models/jobModel/Job.models';
import { UserModel } from 'src/mongodb/models/userModel/User.models';
import * as crypto from 'crypto'
import { JihuoModel } from 'src/mongodb/models/jihuoModel/jihuoModel';
import { OperatService } from '../../operatApi/operat.service';
import { QudaobaoModel } from 'src/mongodb/models/qudaobaoModel/qudaobaoModel';

@Controller('index')
export class BaominController {

    constructor(
        @InjectModel(BaoMinModel) private readonly baoMin: ModelType<BaoMinModel>,
        @InjectModel(JobModel) private jobModel: ModelType<JobModel>,
        @InjectModel(UserModel) private readonly user: ModelType<UserModel>,
        @InjectModel(JihuoModel) private readonly jihuo: ModelType<JihuoModel>,
        @InjectModel(QudaobaoModel) private readonly qudaobao: ModelType<QudaobaoModel>,
        private readonly operat: OperatService,
    ) { }


    /* 点击报名 */
    @Post('entryWork')
    @UseGuards(AuthGuard("jwt"))
    async entryWork(@Body() body, @User() user: UserModel, @Req() req, @Ip() ip) {
        try {
            if (body.imei) {
                const md5 = crypto.createHash('md5');
                const imeimd5 = md5.update(body.imei).digest('hex')
                try {
                    /* 是否加白 */
                    const channelResult = await this.qudaobao.findOne({ mark: req.dns })
                    /* web模式添加ip信息 */
                    if (channelResult.webmodel) {
                        let parse = JSON.parse(body.imei)
                        parse.ips = ip.match(/\d+.\d+.\d+.\d+/)[0]
                        body.imei = JSON.stringify(parse)
                    }
                    if (!channelResult.whitelist) {
                        // /* 查询数据库是否有该设备 */
                        this.jihuo.findOne({ ditch: req.dns, imeiMd5: imeimd5, type: 'baomin' }).then(baominData => {
                            if (!baominData) {
                                /* 统计渠道包报名次数 */
                                this.qudaobao.updateOne({ mark: req.dns }, { $inc: { totalbaomin: 1, todaybaomin: 1 } }).then()
                                /* 存用户设备信息 */
                                this.jihuo.create({
                                    ditch: req.dns,
                                    imeiMd5: imeimd5,
                                    imei: body.imei,
                                    visitorid: body.visitorId,
                                    platform: body.platform,
                                    createtime: Math.floor(Date.now() / 1000),
                                    type: 'baomin',
                                    userid: channelResult.userid,
                                    username: channelResult.username
                                }).then()
                                this.operat.methodFun(body, req, 'baomin').then()
                            } else {
                                console.log('设备重复报名');
                            }
                        })
                    } else {
                        this.operat.methodFun(body, req, 'baomin').then()
                        console.log('报名加白联调');
                    }
                    return await this.baominjilu(body, user)
                } catch (error) {
                    console.log(error);
                    throw error
                }
            } else {
                console.log("报名异常" + JSON.stringify(body));
                throw '报名手机环境异常,请使用正规手机端打开app哟,或者重启app再试哟'
            }
        } catch (error) {
            console.log(error);
            throw new BadGatewayException(error)
        }
    }


    async baominjilu(body, user) {
        try {
            const baoMinResult = await this.baoMin.findOne({ userid: user._id, jobid: body.id })

            /* 统计兼职报名点击数量 */
            this.jobModel.updateOne({ _id: body.id }, { $inc: { cumulativeregistration: 1, signuptoday: 1 } }).then()

            /* 统计用户报名点击数量 */
            this.user.updateOne({ _id: user._id }, { $inc: { count: 1 } }).then()

            if (baoMinResult) {
                this.baoMin.updateOne({ userid: user._id, jobid: body.id }, { isBaoMin: true }).then()
                return { message: "报名成功", code: 200 }
            } else {
                const joblist = await this.jobModel.findOne({ _id: body.id }, ['title', 'price', 'unit', 'settlement', 'jobIntr', 'jobTime', 'jobAddress', 'jobNum', 'companyData', 'fake'])
                this.baoMin.create({
                    title: joblist.title,
                    price: joblist.price,
                    unit: joblist.unit,
                    settlement: joblist.settlement,
                    jobTime: joblist.jobTime,
                    jobAddress: joblist.jobAddress,
                    jobNum: joblist.jobNum,
                    companyData: joblist.companyData,
                    jobIntr: joblist.jobIntr,
                    isCollect: false,
                    isBaoMin: true,
                    jobid: body.id,
                    userid: user._id,
                    fake: joblist.fake
                }).then()
                return { message: "报名成功", code: 200 }
            }
        } catch (error) {
            console.log(error);
            throw new BadGatewayException(error)
        }
    }

}
